package com.example.tcpclient;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.Socket;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Clent extends Activity {

	private EditText message;
	private Button send;
	private TextView hystory;
	private static Socket socket = null;
	private static DataOutputStream outToServer = null;
	private DataInputStream inFromServer = null;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_clent);
		
		message = (EditText) findViewById(R.id.message);
		send = (Button) findViewById(R.id.send);
		hystory = (TextView) findViewById(R.id.hystory);
		
		socket = new Socket();
		
		send.setOnClickListener(new OnClickListener() {
			
			public void onClick(View view) {				
				new SendAsyncTask().execute(message.getText().toString());
				message.setText("");
				
			}
		});
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.clent, menu);
		return true;
	}
	
	
	private class SendAsyncTask extends AsyncTask<String, Void, String> {
		private String result = null;
		@SuppressWarnings("deprecation")
		protected String doInBackground(String... params) {
			try {
				//socket = new Socket("192.168.0.151", 333);	// соединение с моим сервером все работает аписан на ява данные передаються аналогично
				socket = new Socket("194.0.150.90", 8880);
                InputStream is = socket.getInputStream();
				outToServer = new DataOutputStream(socket.getOutputStream());
				//outToServer.writeUTF(params[0]);
	            outToServer.writeBytes(createJSON());
	            //Log.d("Q", createJSON());
	            //inFromServer = new DataInputStream(socket.getInputStream());



                byte[] b = new byte[is.available()];
                is.read(b);

				/*Вот здесь где мы цепляем данные с сервера inFromServer.readLine() программа дальше нереалезует поток
				т.е. result не записуеться и не возращяеься значение doInBackground(String... params)*/
				result = "I: " +params[0]+ ";\n" + "Server" + new String(b) /*inFromServer.readLine()*/+ ";\n\n";

                try{
                    Thread.sleep(100);
                } catch (Exception ex) {}
                b = new byte[is.available()];
                is.read(b);
                result += "size=" + b.length + " |" + new String(b);

	            outToServer.flush();
            	outToServer.close();
	            inFromServer.close();
	            socket.close();
	            
			} catch (Exception e) {
			
			}
			return result;
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			hystory.append(result);
			
		}
		
	}
	
	private String createJSON() {
		JSONObject jsonArray;
		JSONObject jsonObject;
		
		jsonArray = new JSONObject();
		jsonObject = new JSONObject();

		try {
			jsonArray.put("Type", 0);
			jsonArray.put("Password", "qwerty");
			jsonArray.put("Login", "sv");
			jsonObject.put("Pack", jsonArray);
			jsonObject.put("PackType", 0);
		} catch (JSONException e) {
			
		}
		
		return jsonObject.toString();
	}

}

// {"PacketType":0,"Pack":{"Login":null,"Password":null,"Type":0}}
//ip - 194.0.150.90
//port: 8880